import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 15000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['xxxToken'] = store.getters.token// 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
	 const res = response.data
	 if (res.resultCode == 401) {
	   MessageBox.confirm(res.resultDesc, '重新登录', {
		 confirmButtonText: '重新登录',
		 cancelButtonText: '取消',
		 type: 'warning'
	   }).then(() => {
		 store.dispatch('FedLogOut').then(() => {
		   location.reload()
		 })
	   })
	   return Promise.reject(new Error(res.resultDesc || 'Error'))
	 } else if(res.resultCode == 500){
	   Message({
		 message: res.resultDesc || 'Error',
		 type: 'error',
		 duration: 5 * 1000
	   })
	   return Promise.reject(new Error(res.resultDesc || 'Error'))
	 } else {
	   return res
	 }
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
